<template>
  <div class="node_box">
    <el-table
      :data="filterOutputData"
      style="width: 100%"
      border
      fit
      @selection-change="handleSelectionChange"
    >
      <!-- <el-table-column type="selection" width="50" /> -->
      <el-table-column fixed type="index" label="序号" width="100" />
      <el-table-column prop="indicatorName" label="指标名称" width="100">
        <template #default="{ row }">
          <el-input v-model="row.indicatorName" />
        </template>
      </el-table-column>
      <el-table-column prop="creator" label="创建人" width="100">
        <template #default="{ row }">
          <el-input v-model="row.creator" />
        </template>
      </el-table-column>
      <el-table-column prop="domainId" label="所属指标域" width="140">
        <template #default="{ row }">
          <el-select
            v-model="row.domainId"
            class="m-2"
            placeholder="请选择指标域"
            size="large"
            style="width: 100px"
            @change="handleChange(row.domainId)"
          >
            <el-option
              v-for="item in domainList"
              :key="item.id"
              :label="item.domainName"
              :value="item.id!"
            />
          </el-select>
        </template>
      </el-table-column>
      <el-table-column prop="indicatorGroup" label="所属分组" width="140">
        <template #default="{ row }">
          <el-select
            v-model="row.indicatorGroup"
            class="m-2"
            placeholder="请选择分组"
            size="large"
            style="width: 100px"
          >
            <el-option
              v-for="item in indicatorGroupList"
              :key="item.id"
              :label="item.domainName"
              :value="item.id!"
            />
          </el-select>
        </template>
      </el-table-column>
      <el-table-column prop="description" label="描述" width="100">
        <template #default="{ row }">
          <el-input v-model="row.description" />
        </template>
      </el-table-column>
      <el-table-column prop="abnormalId" label="异常规则" width="100">
        <template #default="{ row }">
          <el-select
            v-model="row.abnormalId"
            placeholder="请选择异常规则"
            size="large"
            style="width: 100px"
          >
            <el-option
              v-for="item in abnormalRules"
              :key="item.id"
              :label="item.abnormalName"
              :value="item.id!"
            />
          </el-select>
        </template>
      </el-table-column>
    </el-table>
    <el-button class="mt-4" type="primary" @click="previous">上一步</el-button>
    <el-button
      class="mt-4"
      type="primary"
      :loading="isSubmitting"
      :disabled="isSubmitting"
      @click="insertIndicator"
    >
      {{ isSubmitting ? "提交中..." : "完成" }}
    </el-button>
  </div>
</template>
<script lang="ts">
export default { name: "CreateIndicator" };
</script>
<script setup lang="ts">
import IndicatorDomainAPI, {
  DomainListParameter,
  DomainListResponse,
  IndicatorList,
  IndicatorChildren,
} from "@/api/indicationManage/domain";
import strategyManageAPI, {
  IndicatorInsertParameter,
  IndicatorCofig,
} from "@/api/strategy/strategyManage";
import indicatorAPI, { AbnormalRulesResponse } from "@/api/indicationManage/indexNew";

// 异常规则列表
const abnormalRules = ref<AbnormalRulesResponse[]>([]);

// 从localStorage获取用户信息
const getUserInfo = () => {
  const userInfoStr = localStorage.getItem("userInfo");
  if (userInfoStr) {
    try {
      return JSON.parse(userInfoStr);
    } catch (error) {
      console.error("解析用户信息失败:", error);
      return null;
    }
  }
  return null;
};

const getAbnormalRules = async () => {
  await indicatorAPI
    .AbnormalRules()
    .then((res) => {
      abnormalRules.value = res.data || [];
    })
    .catch((error) => {
      console.error("获取异常规则失败:", error);
    });
};

// 获取当前用户名
const getCurrentUsername = () => {
  const userInfo = getUserInfo();
  return userInfo?.username || "";
};
const emit = defineEmits(["closeCreateIndicator"]);
const isLoading = ref(false); // 加载状态
const isSubmitting = ref(false); // 提交状态，用于防止重复提交
const route = useRoute();
const router = useRouter();
const domainListParameter = reactive<DomainListParameter>({ dataSourceId: 0 });
const domainListResponse = ref<DomainListResponse>();
const domainList = ref<IndicatorList[]>([]);
const indicatorGroupList = ref<IndicatorChildren[]>();
const indicatorInsertParameter = reactive<IndicatorInsertParameter>({});
const props = defineProps<{
  createIndicatorData: any;
}>();
const form = ref({
  dataSourceId: 0,
  dataSourceName: "",
  outputData: [],
});

const filterOutputData = ref();
const selectedRows = ref([]);
// const outputDataFromIndicatorOutput = ref(JSON.parse(sessionStorage.getItem("outputData") || "[]"));

async function handleQuery() {
  domainListParameter.dataSourceId = form.value.dataSourceId;
  const response = await IndicatorDomainAPI.Select(domainListParameter);
  domainListResponse.value = response;
  domainList.value = domainListResponse.value.indicatorList!;
}

async function handleChange(domainId?: any) {
  indicatorGroupList.value = domainList.value.find((item) => item.id === domainId)?.children;
}

const previous = () => {
  emit("closeCreateIndicator");
};

const handleSelectionChange = (rows: any) => {
  selectedRows.value = rows;
};

const insertIndicator = async () => {
  // 防止重复提交
  if (isSubmitting.value) return;

  isSubmitting.value = true;
  try {
    // 直接使用原始数据，不通过indicatorName查找，避免数据匹配错误
    const indicatorConfigList = form.value.outputData.map((item: any) => {
      // 如果是指标列，设置indicatorGroup
      if (item.typeEnum === 0) {
        item.indicatorGroup = item.indicatorGroup || item.domainId;
      }
      return {
        indicatorName: item.indicatorName || "",
        columnName: item.columnName,
        tableName: item.tableName,
        datasourceId: form.value.dataSourceId,
        dataSourceName: form.value.dataSourceName,
        dataType: item.dataType,
        size: item.size,
        digit: item.digit,
        typeEnum: item.typeEnum,
        aggregationMethod: item.aggregationMethod || "",
        creator: item.creator || getCurrentUsername(),
        domainId: item.indicatorGroup || "",
        description: item.description || "",
        abnormalId: item.abnormalId || 0,
      };
    }) as unknown as IndicatorCofig[];
    indicatorInsertParameter.tableName = props.createIndicatorData.newTableName;
    indicatorInsertParameter.indicators = indicatorConfigList;
    console.log(indicatorInsertParameter);
    await strategyManageAPI.insert(indicatorInsertParameter).then((data) => {
      ElMessage.success("添加成功");
      router.push({
        name: "IndicationManage",
        query: {
          dataSourceId: form.value.dataSourceId,
        },
      });
    });
  } catch (error) {
    console.log(error);
    ElMessage.error("添加指标失败！！！");
  } finally {
    isSubmitting.value = false;
  }
};

onMounted(() => {
  // const data = route.query.indicatorOutputData;
  if (props.createIndicatorData) {
    // 获取异常规则列表
    getAbnormalRules();
    form.value.dataSourceId = props.createIndicatorData.dataSourceId;
    form.value.dataSourceName = props.createIndicatorData.dataSourceName;
    form.value.outputData = props.createIndicatorData.columns as [];
    filterOutputData.value = form.value.outputData.filter((item: any) => item.typeEnum == 0);
  }
  handleQuery();
});
</script>
